package hydrap2p.proxy.manager;

import hydrap2p.ServiceLocation;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class NetworkWriter {
	private ByteArrayOutputStream tempoutput;
	private StreamMultiplexer output;
	
	public NetworkWriter(StreamMultiplexer output)
	{
		tempoutput=new ByteArrayOutputStream();
		this.output=output;
	}

	public static final byte[] serializeInt(int value) {
        return new byte[] {
                (byte)(value >>> 24),
                (byte)(value >>> 16),
                (byte)(value >>> 8),
                (byte)value};
	}
	
	public void writeByte(byte val)
	{
		try {
			tempoutput.write(new byte[] {val});
		} catch (IOException e) {
			// Shouldn't happen
			e.printStackTrace();
		}
	}
	
	public void writeBytes(byte[] val)
	{
		writeBytes(val,val.length);
	}
	
	public void writeBytes(byte[] val, int size)
	{
		writeInt(size);
		tempoutput.write(val, 0, size);
	}
	
	public void writeInt(int val)
	{
		try {
			tempoutput.write(serializeInt(val));
		} catch (IOException e) {
			// Shouldn't happen
			e.printStackTrace();
		}
	}
	
	public void writeString(String val)
	{
		Charset utf=Charset.forName("UTF-8");
		byte[] temp=val.getBytes(utf);
		writeBytes(temp);
	}
	
	public void writeServiceLocation(ServiceLocation val)
	{
		writeString(val.address);
		writeInt(val.port);
	}
	
	public void flush(byte command) throws IOException
	{
		ByteArrayOutputStream finaloutput=new ByteArrayOutputStream();
		finaloutput.write(new byte[] {command});
		finaloutput.write(serializeInt(tempoutput.size()));
		finaloutput.write(tempoutput.toByteArray());
		output.send(finaloutput.toByteArray());
	}
}
